package com.umeox.iqibla.custom_tasbih.data

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.umeox.watch.moto.apiclient.model.SubmitTaskRecordDTO
import com.umeox.watch.moto.apiclient.model.TaskRecordAdditionalInfoDTO
import com.umeox.watch.moto.apiclient.model.TaskRecordDTO
import com.umeox.watch.moto.apiclient.model.TaskRecordInfoDTO
import com.umeox.watch.moto.dataservice.proxy.PullApiClientProxy
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

object TasbihTaskListManager {

    private val taskList = mutableListOf<TaskRecordDTO>()

    private val taskListLiveData = MutableLiveData<List<TaskRecordDTO>>(taskList)

    private var requestId = ""

    val taskListObservable: LiveData<List<TaskRecordDTO>> = taskListLiveData

    fun updateTaskList(recordInfoDTO: TaskRecordInfoDTO) {
        requestId = recordInfoDTO.requestId
        taskList.clear()
        taskList.addAll(recordInfoDTO.details)
        taskListLiveData.postValue(taskList)
    }

    fun getTaskByIndex(index: Int): TaskRecordDTO? {
        if (index >= taskList.size) {
            return null
        }
        return taskList[index]
    }

    fun updateTaskProgressByIndex(index: Int, progress: Int) {
        if (index >= taskList.size) {
            return
        }
        val target = taskList[index]
        target.additionalInfo.amount = progress - target.additionalInfo.completed
        target.additionalInfo.completed = progress
        taskListLiveData.postValue(taskList)
    }

    fun submitTaskRecordDTOByIndex(index: Int, startTime: Long) {
        if (index >= taskList.size) {
            return
        }
        val target = taskList[index]
        val submitTaskRecordDTO = SubmitTaskRecordDTO()
        submitTaskRecordDTO.id = target.id
        submitTaskRecordDTO.completeTime =
            SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).format(Date())
        submitTaskRecordDTO.startTime =
            SimpleDateFormat("yyyyMMdd'T'HHmmssZ", Locale.ENGLISH).format(Date(startTime))
        val additionalInfoDTO = TaskRecordAdditionalInfoDTO()
        additionalInfoDTO.azkarIndex = target.additionalInfo.azkarIndex
        additionalInfoDTO.goals = target.additionalInfo.goals
        additionalInfoDTO.completed = target.additionalInfo.completed
        additionalInfoDTO.amount = target.additionalInfo.amount
        submitTaskRecordDTO.additionalInfo = additionalInfoDTO
        GlobalScope.launch(Dispatchers.IO) {
            try {
                PullApiClientProxy.fetchBinder()
                    .submitTaskRecord(requestId, listOf(submitTaskRecordDTO))
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

}